package alg20241113;

public class Text3 {
    public int pivotIndex1(int[] nums) {
        int n = nums.length;
        //1创建表
        int[] f = new int[n];  //前缀和   [0 ~ i - 1] 的和
        int[] g = new int[n];   //后缀和   [i + 1 ~ n - 1] 的和
        //2初始化
        f[0] = 0;
        g[n - 1] = 0;

        //3填表
        for (int i = 1; i < n; i++) {
            f[i] = f[i - 1] + nums[i-1];
        }
        for (int i = n - 2; i > 0; i--) {
            g[i] = g[i + 1] + nums[i + 1];
        }
        //4比较
        for (int i = 0; i < n; i++) {
            if(f[i] == g[i]) return i;
        }
        return -1;
    }

    public int pivotIndex(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            dp[i] = dp[i - 1] + nums[i];
        }

        for (int i = 1; i <= n; i++) {
            if (dp[n] - dp[i] == dp[i - 1]) {
               return i - 1;
            }
        }
        return -1;

    }

}
